<?php

declare(strict_types=1);

namespace core;

class Flash
{
    const FLASH = 'flash_messages';

    /**
     * Flash a message
     *
     * @param string $name (danger, warning, info, success)
     * @param string $message
     */
    public static function add(string $name = '', string $message = '')
    {
        if ($name !== '' && $message !== '') {
            self::create($name, $message);
        } elseif ($name !== '' && $message === '') {
            self::display($name);
        } elseif ($name === '' && $message === '') {
            self::all();
        }
    }

    /**
     * Create a flash message 
     * 
     * @param string $name
     * @param string $message
     * @param string $type
     * @return void
     */
    public static function create(string $name, string $message): void
    {
        // remove existing message with the name
        if (isset($_SESSION[self::FLASH][$name])) {
            unset($_SESSION[self::FLASH][$name]);
        }
        // add the message to the session
        $_SESSION[self::FLASH][$name] = [
            'name'    => $name,
            'message' => $message,
        ];
    }

    /**
     * Format a flash message
     *
     * @param array $flash_message
     * @return string
     */
    public static function format(array $flash_message): string
    {
        return sprintf(
            '<div class="alert alert-%s">%s</div>',
            $flash_message['name'],
            $flash_message['message']
        );
    }

    /**
     * Display a flash message
     *
     * @param string $name
     * @return void
     */
    public static function display(string $name): void
    {
        if (!isset($_SESSION[self::FLASH][$name])) {
            return;
        }

        // get message from the session
        $flash_message = $_SESSION[self::FLASH][$name];

        // delete the flash message
        unset($_SESSION[self::FLASH][$name]);

        // display the flash message
        echo self::format($flash_message);
    }

    /**
     * Display all flash messages
     *
     * @return void
     */
    public static function all(): void
    {
        if (!isset($_SESSION[self::FLASH])) {
            return;
        }

        // get flash messages
        $flash_messages = $_SESSION[self::FLASH];

        // remove all the flash messages
        unset($_SESSION[self::FLASH]);

        // show all flash messages
        foreach ($flash_messages as $flash_message) {
            echo self::format($flash_message);
        }
    }
}
